package com.dhcc.core.modules.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.dhcc.core.cxf.staticWs.WSDLAPPUtil;
import com.dhcc.core.cxf.util.CxfUtil;
import com.dhcc.core.framework.annotion.BussinessLog;
import com.dhcc.core.framework.annotion.CacheClear;
import com.dhcc.core.framework.annotion.Permission;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.constant.Const;
import com.dhcc.core.framework.datascope.DataScope;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.JsonUtil;
import com.dhcc.core.modules.system.cache.config.ConfigCache;
import com.dhcc.core.modules.system.cache.dept.DeptCache;
import com.dhcc.core.modules.system.cache.dept.IDeptCache;
import com.dhcc.core.modules.system.cache.user.IUserCache;
import com.dhcc.core.modules.system.cache.user.UserCache;
import com.dhcc.core.modules.system.entity.Dept;
import com.dhcc.core.modules.system.service.IDeptService;
import com.dhcc.core.modules.system.vo.ExportDeptVo;
import com.dhcc.core.modules.system.warpper.DeptWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 部门控制器
 *
 * @ClassName: DeptController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:15:00
 */
@Controller
@RequestMapping("${sys.backendPath}/dept")
public class DeptController extends BaseController {

    private String PREFIX = "/backend/system/dept/";

    @Autowired
    IDeptService deptService;

    /**
     * 跳转到部门管理首页
     */
    @RequestMapping
    public String index() {
        return PREFIX + "dept.html";
    }

    /**
     * 跳转到添加部门
     */
    @Permission("dept:add")
    @RequestMapping("/dept_add")
    public String deptAdd() {
        return PREFIX + "dept_add.html";
    }

    /**
     * 跳转到修改部门
     */
    @Permission("dept:update")
    @RequestMapping("/dept_update/{deptId}")
    public String deptUpdate(@PathVariable Long deptId, Model model) {
        Dept dept = deptService.selectById(deptId);
        model.addAttribute(dept);
        model.addAttribute("parentName", DeptCache.me().getDeptNameById(dept.getParentId()));
        model.addAttribute("leaderName", UserCache.me().getUserNameById(dept.getLeader()));
        model.addAttribute("superiorName", UserCache.me().getUserNameById(dept.getSuperior()));
        return PREFIX + "dept_edit.html";
    }

    /**
     * 获取部门的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        //return DeptCache.me().getDeptTree();
        return DeptCache.me().getDeptTreeScope();
    }

    /**
     * 新增部门
     */
    @BussinessLog(value = "添加部门")
    @RequestMapping(value = "/add")
    @Permission("dept:add")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public Object add(Dept dept) {
        if (CommonUtil.isOneEmpty(dept, dept.getName())) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        dept.init();
        return this.deptService.insert(dept);
    }

    /**
     * 获取所有部门列表
     */
    @RequestMapping(value = "/list")
    @Permission("dept:list")
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue="0") Long parentId, @RequestParam(required = false, defaultValue="") String condition) {
        List<Dept> list =null;
        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {//判断是否为超级管理员
            list = this.deptService.list(parentId,condition);
        }
        else
        {
            DataScope dataScope = new DataScope(ShiroKit.getDepDataScope());
            list = this.deptService.list(dataScope,parentId,condition);
        }

        return super.warpObject(new DeptWarpper(list));
    }

    @RequestMapping(value = "/query/{parentId}")
    @Permission("dept:list")
    @ResponseBody
    public Object query(@PathVariable(required = false) Long parentId, @RequestParam(required = false, defaultValue="") String condition) {
        List<Dept> list =null;
        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {//判断是否为超级管理员
            list = this.deptService.list(parentId,condition);
        }
        else
        {
            DataScope dataScope = new DataScope(ShiroKit.getDepDataScope());
            list = this.deptService.list(dataScope,parentId,condition);
        }

        return super.warpObject(new DeptWarpper(list));
    }

    /**
     * 部门详情
     */
    @RequestMapping(value = "/detail/{deptId}")
    @Permission("dept:detail")
    @ResponseBody
    public Object detail(@PathVariable("deptId") Long deptId) {
        return deptService.selectById(deptId);
    }

    /**
     * 修改部门
     */
    @BussinessLog(value = "修改部门")
    @RequestMapping(value = "/update")
    @Permission("dept:update")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public Object update(Dept dept) {
        if (CommonUtil.isEmpty(dept) || dept.getId() == null) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        Dept old = deptService.selectById(dept.getId());
        old.setCode(dept.getCode());
        old.setHisCode(dept.getHisCode());
        old.setDescription(dept.getDescription());
        old.setFullname(dept.getFullname());
        old.setInitials(dept.getInitials());
        old.setLeader(dept.getLeader());
        old.setName(dept.getName());
        old.setPinyin(dept.getPinyin());
        old.setSuperior(dept.getSuperior());
        old.setWeight(dept.getWeight());
        old.setParentId(dept.getParentId());
        old.setDeptType(dept.getDeptType());
        old.setDeptAttr(dept.getDeptAttr());
        old.setDeptGroup(dept.getDeptGroup());
        old.setLongit(dept.getLongit());
        old.setLatit(dept.getLatit());
        old.init();
        deptService.updateAllColumnById(old);
        return R.ok();
    }

    /**
     * 删除部门
     */
    @BussinessLog(value = "删除部门")
    @RequestMapping(value = "/delete")
    @Permission("dept:delete")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public Object delete(@RequestParam Long deptId) {
        // 缓存被删除的部门
        try {
            deptService.delDept(deptId);
        } catch (BizException e){
            return R.error(e.getMsg());
        }
        return R.ok();
    }
    /**
     * 同步·部门
     */
    @BussinessLog(value = "同步部门")
    @RequestMapping(value = "/sync")
    @Permission("dept:sync")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public Object sync(@RequestParam Long deptId) {
        //取系统参数 同步地址平台下需要考虑在组织机构表里增加字段记录该url
        ConfigCache cc =new ConfigCache();
        String urlV = cc.getValueByKey("DeptSyncURL");

        if(CommonUtil.isEmpty(urlV))
        {
            return R.error("同步地址参数未配置。");
        }
        //根据deptId取外部主键id值
        Dept parDept = deptService.selectById(deptId);
        String xCode = parDept.getXcode();
        //是否webservice有密码
        boolean pwdFalg = parDept.getPwdFlag();
        if(CommonUtil.isEmpty(xCode))
        {
            return R.error("同步医院外部主键未配置。");
        }
        Integer count =0;
        Integer currNo =1,limit=10;
        boolean flag =true;
        while((flag)) {
            Integer start = (currNo-1)*limit+1;
            Object data =null;
            if(pwdFalg)
            {
                //需要密码
                data=WSDLAPPUtil.queryDepts(urlV, xCode, "E|W", start.toString(), limit.toString());
            }
            else
            {
                String nUrl ="";
                if(urlV.contains("http:"))
                {
                    nUrl = urlV+"/DHCHAI.IO.AppService.CLS?WSDL";
                }
                else
                    nUrl = "http://"+urlV+"/DHCHAI.IO.AppService.CLS?WSDL";
                data = CxfUtil.invoke(nUrl, "QueryDepts", xCode,"E|W",start.toString(),limit.toString());
            }
            if(CommonUtil.isEmpty(data))
            {
                flag=false;
                continue;
            }
            String[] arrJsonStr = data.toString().split("#");

            for(int i=0;i<arrJsonStr.length;i++)
            {
                JSONObject objJs = JsonUtil.parseObj(arrJsonStr[i]);

                //{"KeyId":"20","LocCode":"ZYMZ020","LocDesc":"耳鼻咽喉门诊","LocDesc2":"耳鼻咽喉门诊",
                //"LocHospDr":"1","LocTypeCode":"E","LocTypeDesc":"执行科室","GroupCode":"07","GroupDesc":"其他科","IsOPER":"       否","IsICU":"否","IsNICU":"否","IsActive":"是"}
                Dept dept;
                dept = deptService.selectByCode(parDept.getCode()+objJs.getString("LocCode"));
                if (CommonUtil.isEmpty(dept) || dept.getId() == null) {
                    dept=new Dept();
                }

                dept.setCode(parDept.getCode()+objJs.getString("LocCode"));  //唯一性

                dept.setDescription(objJs.getString("LocDesc"));
                dept.setName(objJs.getString("LocDesc2"));
                dept.setParentId(deptId);
                dept.setFullname(objJs.getString("LocDesc"));

                String LocTypeCode=objJs.getString("LocTypeCode");
                if (LocTypeCode=="E") {
                    dept.setDeptType("3");
                }else if (LocTypeCode=="W") {
                    dept.setDeptType("4");
                }
                dept.setXcode(objJs.getString("KeyId"));
                if(CommonUtil.equals(objJs.getString("IsOPER"), "是"))
                {
                    if(CommonUtil.contains(dept.getDeptAttr(), "1,"))
                    {
                        //
                    }
                    else
                    {
                        if(CommonUtil.isEmpty(dept.getDeptAttr()))
                            dept.setDeptAttr("1,");
                        else
                            dept.setDeptAttr(dept.getDeptAttr()+"1,");
                    }
                }
                if(CommonUtil.equals(objJs.getString("IsICU"), "是"))
                {
                    if(CommonUtil.contains(dept.getDeptAttr(), "2,"))
                    {
                        //
                    }
                    else
                    {
                        if(CommonUtil.isEmpty(dept.getDeptAttr()))
                            dept.setDeptAttr("2,");
                        else
                            dept.setDeptAttr(dept.getDeptAttr()+"2,");
                    }
                }
                if(CommonUtil.equals(objJs.getString("IsNICU"), "是"))
                {
                    if(CommonUtil.contains(dept.getDeptAttr(), "3,"))
                    {
                        //
                    }
                    else
                    {
                        if(CommonUtil.isEmpty(dept.getDeptAttr()))
                            dept.setDeptAttr("3,");
                        else
                            dept.setDeptAttr(dept.getDeptAttr()+"3,");
                    }
                }
                dept.setPwdFlag(true);
                dept.init();

                if (dept.getId() != null) {
                    this.deptService.updateAllColumnById(dept);
                    count++;

                }   else {
                    this.deptService.insert(dept);
                    count++;

                }
            }
            currNo++;
            //测试时导入部分页结束
            /*
            if(currNo>2)
        	{
        		flag=false;
        	}
        	*/
        }
        return R.ok(count.toString());
    }
    /**
     * 同步·科室(t_cdc_ct_location表)
     */
    @BussinessLog(value = "同步部门")
    @RequestMapping(value = "/syncDept")
    @Permission("dept:sync")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public Object syncDept(@RequestParam Long deptId) {
        Integer count = this.deptService.syncDept(deptId);
        return R.ok(count.toString());
    }
    /**
     * 导出科室
     */
    @Permission("dept:export")
    @RequestMapping("/export")
    public void exportDepts(@RequestParam(required = false) String condition, HttpServletRequest request, HttpServletResponse response) {
        List<ExportDeptVo> result = this.deptService.exportDepts(condition);

        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        // 一次性写出内容，使用默认样式
        if (CommonUtil.isNotEmpty(result)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            for (ExportDeptVo obj : result) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("机构编码",obj.getCode());
                row.put("机构简称",obj.getName());
                row.put("机构全称",obj.getFullName());
                row.put("HIS编码",obj.getHisCode());
                row.put("机构类型",obj.getDeptType());
                row.put("备注",obj.getDescription());
                rows.add(row);
            }
            writer.write(rows);
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 30);
            writer.setColumnWidth(2, 30);
            writer.setColumnWidth(3, 25);
            writer.setColumnWidth(4, 10);
            writer.setColumnWidth(5, 40);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        ServletOutputStream out = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "机构_" + sdf.format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
            out = response.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }
    /**
     * 跳转到导入科室的页面
     */
    @Permission("dept:import")
    @RequestMapping("/to_import/{parentId}")
    public String toImport(@PathVariable Long parentId, Model model) {
        model.addAttribute("parentId",parentId);
        return PREFIX + "import.html";
    }
    /**
     * 导入科室
     */
    @Permission("dept:import")
    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    @CacheClear({IDeptCache.CACHE_NAME,IUserCache.CACHE_NAME})
    public R importDepts(@RequestPart("file") MultipartFile file, @RequestParam("parentId") Long parentId) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> all = reader.read();
            this.deptService.importDepts(all, parentId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return R.ok();
    }
}
